package com.dkd.app.controller;


import cn.elegent.pay.ElegentPay;
import cn.elegent.pay.constant.Platform;
import cn.elegent.pay.constant.TradeType;
import cn.elegent.pay.dto.*;
import com.dkd.app.domain.Order;
import com.dkd.app.domain.dto.PayDto;
import com.dkd.app.domain.vo.SkuVo;
import com.dkd.app.service.OrderService;
import com.dkd.app.service.SkuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private ElegentPay elegentPay;

    @Autowired
    private SkuService skuService;

    @Autowired
    private OrderService orderService;

    /**
     * 支付
     */
    @PostMapping("/requestPay/{tradeType}/{platform}")
    public PayResponse requestPay(@RequestBody  PayDto payDto,
                                  @PathVariable("tradeType") String tradeType,
                                  @PathVariable("platform") String platform) {

        validatePlatformAndOrder(tradeType, platform);

        PayRequest payRequest = new PayRequest();
        payRequest.setOrderSn(System.currentTimeMillis()+""); //订单号
        payRequest.setBody(queryProductNameBySkuId(payDto.getSkuId())); // 商品名称
        payRequest.setTotalFee(calculateTotalFee(payDto.getSkuId())); // 金额分


        // 设置openId（对于小程序支付是必须的）
        if (TradeType.JSAPI.equals(tradeType)) {
            payRequest.setOpenid(payDto.getOpenId());
            if (payDto.getOpenId() == null || payDto.getOpenId().isEmpty()) {
                throw new IllegalArgumentException("对于JSAPI支付，OpenID是必需的。");
            }
        }

        // 校验并设置交易类型
        if (!isValidTradeType(tradeType)) {
            throw new IllegalArgumentException("无效的交易类型: " + tradeType);
        }

        // 校验并设置平台类型
        if (!isValidPlatform(platform)) {
            throw new IllegalArgumentException("无效的平台类型: " + platform);
        }

        // 调用ElegentPay的支付请求方法
        PayResponse payResponse = elegentPay.requestPay(payRequest, tradeType, platform);
        return payResponse;
    }

    /**
     * 关闭订单
     * @param orderNo
     * @return
     */
    @GetMapping("/closeOrder/{orderNo}/{platform}")
    public Boolean closeOrder(@PathVariable("orderNo") String orderNo,@PathVariable("platform") String platform){
        Boolean aBoolean = elegentPay.closePay(orderNo,platform);
        return aBoolean;
    }

    /**
     * 退款
     * @param orderNo
     * @return
     */
    @GetMapping("/refund/{orderNo}/{platform}")
    public boolean refund(@PathVariable("orderNo") String orderNo,@PathVariable("platform") String platform){

        // 根据订单号查询订单信息
        Order order = orderService.getById(orderNo);

        RefundRequest refundRequest=new RefundRequest();
        refundRequest.setTotalFee(order.getPrice());
        refundRequest.setRefundAmount(order.getAmount());
        refundRequest.setOrderSn(orderNo);
        refundRequest.setRequestNo(System.currentTimeMillis()+"");
        Boolean refund = elegentPay.refund(refundRequest,platform);
        return refund;
    }

    /**
     * 查询订单
     * @param orderNo
     * @return
     */
    @GetMapping("/query/{orderNo}/{platform}")
    public QueryResponse query(@PathVariable("orderNo") String orderNo,@PathVariable("platform") String platform){
        QueryResponse queryResponse = elegentPay.queryTradingOrderNo(orderNo,platform);
        return queryResponse;
    }

    /**
     * 查询退款订单
     * @param orderNo
     * @return
     */
    @GetMapping("/queryRefund/{orderNo}/{platform}")
    public QueryRefundResponse queryRefund(@PathVariable("orderNo") String orderNo,@PathVariable("platform") String platform){
        QueryRefundResponse queryRefundResponse = elegentPay.queryRefundTrading(orderNo,platform);
        return queryRefundResponse;
    }
    /**
     * 验证并转换平台类型字符串为有效的平台标识符。
     */
    private void validatePlatform(String platformStr) {
        if (!isValidPlatform(platformStr)) {
            throw new IllegalArgumentException("无效的平台类型: " + platformStr);
        }
    }

    /**
     * 校验平台类型和订单号。
     */
    private void validatePlatformAndOrder(String orderNo, String platformStr) {
        if (orderNo == null || orderNo.trim().isEmpty()) {
            throw new IllegalArgumentException("无效的订单号。");
        }
        validatePlatform(platformStr);
    }


    /**
     * 校验交易类型是否有效。
     */
    private boolean isValidTradeType(String tradeType) {
        return TradeType.NATIVE.equals(tradeType) ||
                TradeType.JSAPI.equals(tradeType) ||
                TradeType.APP.equals(tradeType) ||
                TradeType.H5.equals(tradeType);
    }

    /**
     * 校验平台是否有效。
     */
    private boolean isValidPlatform(String platform) {
        return Platform.WX.equals(platform) || Platform.ALI.equals(platform);
    }


    /**
     * 根据商品ID查询商品名称。
     */
    private String queryProductNameBySkuId(Long skuId) {
        SkuVo skuInfo = skuService.findSkuNameAndPriceById(skuId);
        return skuInfo.getSkuName();
    }

    /**
     * 根据商品ID计算总金额。
     */
    private Integer calculateTotalFee(Long skuId) {
        SkuVo skuInfo = skuService.findSkuNameAndPriceById(skuId);
        return skuInfo.getPrice();
    }
}
